<template>
  <div class="question-manage-container">
    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="题库选择">
          <el-select v-model="searchForm.bankId" placeholder="请选择题库" clearable>
            <el-option
              v-for="bank in questionBanks"
              :key="bank.id"
              :label="bank.name"
              :value="bank.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题型选择">
          <el-select v-model="searchForm.type" placeholder="请选择题型" clearable>
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
            <el-option label="判断题" value="true-false" />
            <el-option label="问答题" value="essay" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入题目关键词"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="排序方式">
          <el-select v-model="searchForm.sortBy" placeholder="请选择排序方式">
            <el-option label="创建时间" value="createdAt" />
            <el-option label="题号" value="id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <el-button type="primary" @click="showAddDialog">添加题目</el-button>
      <el-button type="success" @click="handleExport">导出题目</el-button>
    </div>

    <!-- 题目列表 -->
    <el-table :data="questions" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="题号" width="100" />
      <el-table-column prop="bankName" label="所属题库" width="150" />
      <el-table-column prop="title" label="标题" show-overflow-tooltip />
      <el-table-column prop="type" label="题型" width="100">
        <template #default="{ row }">
          {{ getQuestionTypeText(row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <div class="total-count">共 {{ total }} 条</div>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10]"
        layout="prev, pager, next, jumper"
        :total="total"
        :pager-count="5"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加题目' : '编辑题目'"
      width="700px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="所属题库" required>
          <el-select v-model="form.bankId" placeholder="请选择题库">
            <el-option
              v-for="bank in questionBanks"
              :key="bank.id"
              :label="bank.name"
              :value="bank.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题型" required>
          <el-select v-model="form.type" placeholder="请选择题型">
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
            <el-option label="判断题" value="true-false" />
            <el-option label="问答题" value="essay" />
          </el-select>
        </el-form-item>
        <el-form-item label="题目" required>
          <el-input v-model="form.title" type="textarea" :rows="3" placeholder="请输入题目内容" />
        </el-form-item>
        <el-form-item label="选项" v-if="form.type === 'single' || form.type === 'multiple'">
          <div v-for="(option, index) in form.options" :key="index" class="option-item">
            <el-input v-model="option.text" placeholder="请输入选项内容">
              <template #prepend>
                <el-checkbox v-model="option.isCorrect" />
              </template>
            </el-input>
            <el-button type="danger" link @click="removeOption(index)" v-if="form.options.length > 2">
              删除
            </el-button>
          </div>
          <el-button type="primary" link @click="addOption" v-if="form.options.length < 6">
            添加选项
          </el-button>
        </el-form-item>
        <el-form-item label="答案" v-if="form.type === 'true-false'">
          <el-radio-group v-model="form.answer">
            <el-radio label="true">正确</el-radio>
            <el-radio label="false">错误</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="答案" v-if="form.type === 'essay'">
          <el-input v-model="form.answer" type="textarea" :rows="3" placeholder="请输入参考答案" />
        </el-form-item>
        <el-form-item label="解析">
          <el-input v-model="form.analysis" type="textarea" :rows="3" placeholder="请输入题目解析" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getQuestionBanks } from '@/api/questionBank';
import type { QuestionBank } from '@/api/questionBank';
import { getQuestions, createQuestion, updateQuestion, deleteQuestion } from '@/api/question';
import type { Question, CreateQuestionData } from '@/api/question';

const route = useRoute();

// 搜索表单
const searchForm = ref({
  bankId: route.query.bankId as string || '',
  type: '' as Question['type'] | '',
  keyword: '',
  sortBy: 'createdAt'
});

// 题目列表
const questions = ref<Question[]>([]);
const questionBanks = ref<QuestionBank[]>([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框
const dialogVisible = ref(false);
const dialogType = ref<'add' | 'edit'>('add');
const form = ref<CreateQuestionData>({
  bankId: '',
  type: 'single',
  title: '',
  options: [
    { text: '', isCorrect: false },
    { text: '', isCorrect: false }
  ],
  answer: '',
  analysis: ''
});

// 获取题库列表
const fetchQuestionBanks = async () => {
  try {
    const response = await getQuestionBanks();
    questionBanks.value = response.data;
    // 如果有题库数据，优先使用路由参数中的题库ID
    if (questionBanks.value.length > 0) {
      if (!searchForm.value.bankId) {
        searchForm.value.bankId = questionBanks.value[0].id;
      }
      // 确保表单中的题库ID也被设置
      form.value.bankId = searchForm.value.bankId;
      fetchQuestions();
    }
  } catch (error) {
    ElMessage.error('获取题库列表失败');
  }
};

// 获取题目列表
const fetchQuestions = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm.value,
      page: currentPage.value,
      pageSize: pageSize.value
    };
    // 确保题库ID存在
    if (!params.bankId) {
      ElMessage.error('未找到题库ID');
      return;
    }
    // 如果有关键词，进行搜索
    if (params.keyword) {
      params.keyword = params.keyword.trim();
    }
    const response = await getQuestions(params);
    questions.value = response.data;
    total.value = response.total;
  } catch (error) {
    ElMessage.error('获取题目列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  fetchQuestions();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    bankId: questionBanks.value.length > 0 ? questionBanks.value[0].id : '',
    type: '',
    keyword: '',
    sortBy: 'createdAt'
  };
  handleSearch();
};

// 监听题库选择变化
watch(() => searchForm.value.bankId, () => {
  handleSearch();
});

// 监听关键词变化
watch(() => searchForm.value.keyword, (newVal) => {
  if (newVal === '') {
    handleSearch();
  }
});

// 显示添加对话框
const showAddDialog = () => {
  if (!searchForm.value.bankId) {
    ElMessage.error('请先选择题库');
    return;
  }
  dialogType.value = 'add';
  form.value = {
    bankId: searchForm.value.bankId,
    type: 'single',
    title: '',
    options: [
      { text: '', isCorrect: false },
      { text: '', isCorrect: false }
    ],
    answer: '',
    analysis: ''
  };
  dialogVisible.value = true;
};

// 编辑处理
const handleEdit = (row: Question) => {
  dialogType.value = 'edit';
  form.value = {
    bankId: row.bankId,
    type: row.type,
    title: row.title,
    options: row.options,
    answer: row.answer,
    analysis: row.analysis
  };
  // 保存题目ID用于更新
  (form.value as any).id = row.id;
  dialogVisible.value = true;
};

// 删除处理
const handleDelete = async (row: Question) => {
  try {
    await ElMessageBox.confirm('确定要删除该题目吗？', '提示', {
      type: 'warning'
    });
    await deleteQuestion(row.id);
    ElMessage.success('删除成功');
    fetchQuestions();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 导出处理
const handleExport = () => {
  // TODO: 实现导出功能
  ElMessage.info('导出功能开发中');
};

// 添加选项
const addOption = () => {
  form.value.options.push({ text: '', isCorrect: false });
};

// 删除选项
const removeOption = (index: number) => {
  form.value.options.splice(index, 1);
};

// 提交表单
const handleSubmit = async () => {
  if (!form.value.bankId || !form.value.type || !form.value.title) {
    ElMessage.warning('请填写必填项');
    return;
  }

  try {
    if (dialogType.value === 'add') {
      await createQuestion(form.value);
      ElMessage.success('添加成功');
    } else {
      const id = (form.value as any).id;
      await updateQuestion(id, form.value);
      ElMessage.success('更新成功');
    }
    dialogVisible.value = false;
    fetchQuestions();
  } catch (error) {
    ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败');
  }
};

// 分页处理
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchQuestions();
};

// 格式化日期
const formatDate = (date: string) => {
  return new Date(date).toLocaleString();
};

// 获取题型文本
const getQuestionTypeText = (type: Question['type']) => {
  const typeMap: Record<Question['type'], string> = {
    single: '单选题',
    multiple: '多选题',
    'true-false': '判断题',
    essay: '问答题'
  };
  return typeMap[type] || type;
};

onMounted(() => {
  fetchQuestionBanks();
  fetchQuestions();
});
</script>

<style scoped>
.question-manage-container {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 20px;
}

.total-count {
  color: #606266;
}

.option-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>